package brands

import (
	"context"
	"encoding/json"
	"github.com/gin-gonic/gin"
	"go.uber.org/zap"
	"net/http"
	"strconv"
	"web/goods/api"
	"web/goods/forms"
	"web/goods/global"
	"web/goods/proto"
)

// 获取品牌列表
func GetBrandsList(ctx *gin.Context) {
	request := new(proto.BrandFilterRequest)

	pages := ctx.DefaultQuery("pn", "0")
	pagesInt, _ := strconv.Atoi(pages)
	request.Pages = int32(pagesInt)

	perNums := ctx.DefaultQuery("pnum", "0")
	perNumsInt, _ := strconv.Atoi(perNums)
	request.PagePerNums = int32(perNumsInt)

	rsp, err := global.GoodsSrvClient.BrandList(context.Background(), request)
	if err != nil {
		api.HandleGrpcErrorToHttp(err, ctx)
		return
	}

	ctx.JSON(http.StatusOK, rsp)
}

// 创建品牌
func CreateBrand(ctx *gin.Context) {
	f := new(forms.CreateBrandForm)
	if err := ctx.ShouldBind(&f); err != nil {
		api.HandleValidatorError(ctx, err)
		return
	}

	rsp, err := global.GoodsSrvClient.CreateBrand(context.Background(), &proto.BrandRequest{
		Name: f.Name,
		Logo: f.Logo,
	})
	if err != nil {
		api.HandleGrpcErrorToHttp(err, ctx)
		return
	}

	ctx.JSON(http.StatusOK, rsp)
}

// 修改品牌
func UpdateBrand(ctx *gin.Context) {
	idStr := ctx.Param("id")
	idInt, err := strconv.Atoi(idStr)
	if err != nil {
		zap.S().Error("strconv.Atoi：string转int类型发生错误")
		ctx.JSON(http.StatusNotFound, gin.H{
			"msg": "解析参数出错，请检查品牌id参数",
		})
		return
	}

	raw, _ := ctx.GetRawData()
	f := new(forms.CreateBrandForm)
	json.Unmarshal(raw, &f)

	_, err = global.GoodsSrvClient.UpdateBrand(context.Background(), &proto.BrandRequest{
		Id:   int32(idInt),
		Name: f.Name,
		Logo: f.Logo,
	})
	if err != nil {
		api.HandleGrpcErrorToHttp(err, ctx)
		return
	}

	ctx.JSON(http.StatusOK, gin.H{
		"msg": "修改成功",
	})
}

// 删除品牌
func DeleteBrand(ctx *gin.Context) {
	idStr := ctx.Param("id")
	idInt, err := strconv.Atoi(idStr)
	if err != nil {
		zap.S().Error("strconv.Atoi：string转int类型发生错误")
		ctx.JSON(http.StatusNotFound, gin.H{
			"msg": "解析参数出错，请检查品牌id参数",
		})
		return
	}

	_, err = global.GoodsSrvClient.DeleteBrand(context.Background(), &proto.BrandRequest{
		Id: int32(idInt),
	})
	if err != nil {
		api.HandleGrpcErrorToHttp(err, ctx)
		return
	}
	ctx.JSON(http.StatusOK, gin.H{
		"msg": "删除成功",
	})
}
